package org.arain.spring.captive.portal.config;

import org.arain.spring.captive.portal.server.TCPHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 *
 * @author Arain
 * @date 2019年6月27日 下午7:12:32
 */
@Component
@Qualifier("tCPProtocolInitalizer")
public class TCPProtocolInitalizer extends ChannelInitializer<SocketChannel> {  
  
    @Autowired  
    StringDecoder stringDecoder;  
  
    @Autowired  
    StringEncoder stringEncoder;  
  
    @Autowired  
    TCPHandler serverHandler;  
  
    @Override  
    protected void initChannel(SocketChannel socketChannel) throws Exception {  
     // 请求解码器
        socketChannel.pipeline().addLast("http-decoder", new HttpRequestDecoder());
        // 将HTTP消息的多个部分合成一条完整的HTTP消息
        socketChannel.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65535));
        // 响应转码器
        socketChannel.pipeline().addLast("http-encoder", new HttpResponseEncoder());
        // 解决大码流的问题，ChunkedWriteHandler：向客户端发送HTML5文件
        socketChannel.pipeline().addLast("http-chunked", new ChunkedWriteHandler());
        // 自定义处理handler
        socketChannel.pipeline().addLast("http-server", serverHandler);
    }  
  
    public StringDecoder getStringDecoder() {  
        return stringDecoder;  
    }  
  
    public void setStringDecoder(StringDecoder stringDecoder) {  
        this.stringDecoder = stringDecoder;  
    }  
  
    public StringEncoder getStringEncoder() {  
        return stringEncoder;  
    }  
  
    public void setStringEncoder(StringEncoder stringEncoder) {  
        this.stringEncoder = stringEncoder;  
    }  
  
    public TCPHandler getServerHandler() {  
        return serverHandler;  
    }  
  
    public void setServerHandler(TCPHandler serverHandler) {  
        this.serverHandler = serverHandler;  
    }  
  
}  
